//评估记录
import * as React from 'react';
import {
  Select,
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  notification,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  Button,
  Form,
  message,
  InputNumber,
} from 'antd';
import axios from 'axios';
import Api from '../../services/apis';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from "./style.less";

const confirm = Modal.confirm;
const FormItem = Form.Item;

@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))
class permissionPassword extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: '',
      name: '',
      modalVisible: false,
      modifyVisible: false,
      functionName: '',
      functionCode: '',
      functionDesc: '',
      _permissionType: '',
      permissionType: [],
      permissionTypeList: [],
      current: 1,
      totalSize: 1,
      pageSize: 5,
      tableData: [],
      orgTreeData: [],
      _orgTreeData: [],
      selectedMenu: [],
      functionId: '',
      showTree: false,
    };
  }

  componentWillMount() {
    const that = this;
    console.log('this.props.location.query;', this.props.location.query);

    //获取表格数据
    this.sendData();
    //获取下拉树
    axios.post(Api.umGetMenuTreeByFun, {}).then(function (resp) {
      const {data} = resp;
      if (data) {
        let treeData = new Array(data);
        that.formatTreeData(treeData, 'menuName', 'menuLevelFormat', 'menuId', 'childMenuList');
        that.setState({ orgTreeData: treeData });
      }
    });
    //获取权限类型
    axios.post(Api.umGetDicById, {}).then(function (resp) {
      const {data} = resp;
      if (data) {
        that.setState({ permissionType: data });
      }
    });

    //获取权限类型列表
    axios.post(Api.umGetDicList, {}).then(function (resp) {
      const {data} = resp;
      if (data) {
        that.setState({ permissionTypeList: data });
      }
    });
  }

  //格式化树需要的数据
  formatTreeData = (data, title, key, value, children) => {
    let selectedMenu = this.state.permissionType;

    data.forEach((d, i, arr) => {
      d.title = d[title] ? d[title] : null;
      d.key = d[key] ? d[key] : i;
      d.value = d[value] ? d[value] + '' : '';
      d.children = d[children] ? d[children] : null;
      if (d.fun) {
        selectedMenu.push(d[value] + '');
      }
      if (d[children] && d[children].length != 0) {
        this.formatTreeData(d[children], title, key, value, children);
      }
    });
    this.setState({ permissionType: selectedMenu });
  };

  resetForm() {
    this.setState({
      number: '',
    });
  }

  sendData() {
    const that = this;

    axios
      .post(Api.umGetFunctionList, {
        functionName: this.state.number,
        currentPage: this.state.current,
      })
      .then(function (resp) {
        const {data} = resp;
        if (data.list.length == 0) {
          message.warning('暂无数据');
        }
        let tmp = [];

        for (let i = 0, len = data.list.length; i < len; i++) {
          tmp.push({
            key: i + 1,
            name: data.list[i].functionName ? data.list[i].functionName : '-',
            area: data.list[i].functionCode ? data.list[i].functionCode : '-',
            status: data.list[i].functionDesc ? data.list[i].functionDesc : '-',
            number: data.list[i].modifyDateStr ? data.list[i].modifyDateStr : '-',
            functionId: data.list[i].functionId ? data.list[i].functionId : '-',
            stateCode: data.list[i].stateCode ? data.list[i].stateCode : '-',
            menuFun: data.list[i].menuFun,
            menuId: data.list[i].menuId,
          });
        }
        that.setState({
          tableData: tmp,
          totalSize: data.totalSize,
          pageSize: data.pageSize,
          current: data.currentPage,
        });
      });
  }

  changeNumber = e => {
    this.setState({ number: e.target.value });
  };

  changeUser = (functionId, functionName, functionCode, functionDesc, showTree) => {
    let that = this;
    this.setState({ permissionType: [] });
    let param = new URLSearchParams();
    param.append('functionId', functionId);
    axios.post(Api.umGetMenuTreeByFun, {}).then(function (resp) {
      const {data} = resp;
      if (data) {
        let treeData = new Array(data);
        that.formatTreeData(treeData, 'menuName', 'menuLevelFormat', 'menuId', 'childMenuList');
        that.setState({ _orgTreeData: treeData });
      }
    });
    this.setState({
      modifyVisible: true,
      functionId: functionId,
      functionName: functionName,
      functionCode: functionCode,
      functionDesc: functionDesc,
      showTree: showTree,
    });
  };

  setModalVisible(modalVisible, update) {
    let that = this;
    if (update) {
      axios
        .post(Api.umAddFunction, {
          functionName: this.state.functionName,
          functionType: this.state._permissionType,
          functionCode: this.state.functionCode,
          functionDesc: this.state.functionDesc,
        })
        .then(function (resp) {
          const {data} = resp;
          if (data.code == 1) {
            notification.destroy();
            notification['success']({
              message: data.msg,
            });
            //关闭弹框
            this.setState({
              modalVisible: modalVisible,
            });
            //刷新列表
            that.sendData();
          } else if (data.code == 2) {
            notification.destroy();
            notification['warning']({
              message: data.msg,
            });
          } else if (data.code == 0) {
            notification.destroy();
            notification['error']({
              message: data.msg,
            });
          }
        });
    } else {
      this.setState({
        modalVisible: modalVisible,
      });
    }
  }
  setmodifyVisible = (modifyVisible, update) => {
    let that = this;
    if (update) {
      axios
        .post(Api.umUpdateFunction, {
          functionName: this.state.functionName,
          functionId: this.state.functionId,
          functionCode: this.state.functionCode,
          functionDesc: this.state.functionDesc,
          menuIds: this.state.permissionType,
        })
        .then(function (resp) {
          const {data} = resp;
          if (data.code == 1) {
            notification.destroy();
            notification['success']({
              message: data.msg,
            });
            //关闭弹框
            this.setState({
              modifyVisible: modifyVisible,
            });
            //刷新列表
            that.sendData();
          } else if (data.code == 2) {
            notification.destroy();
            notification['warning']({
              message: data.msg,
            });
          } else if (data.code == 0) {
            notification.destroy();
            notification['error']({
              message: data.msg,
            });
          }
        });
    } else {
      this.setState({
        modifyVisible: modifyVisible,
      });
    }
  };
  frozenUser = id => {
    let that = this;

    axios
      .post(Api.umUpdateFunction, {
        functionId: id,
      })
      .then(function (resp) {
        const {data} = resp;
        if (data.code == 1) {
          notification.destroy();
          notification['success']({
            message: data.msg,
          });
          //刷新列表
          that.sendData();
        } else if (data.code == 2) {
          notification.destroy();
          notification['warning']({
            message: data.msg,
          });
        } else if (data.code == 0) {
          notification.destroy();
          notification['error']({
            message: data.msg,
          });
        }
      });
  };
  functionName = e => {
    this.setState({ functionName: e.target.value });
  };

  functionCode = e => {
    this.setState({ functionCode: e.target.value });
  };

  functionDesc = e => {
    this.setState({ functionDesc: e.target.value });
  };

  addpermissionType = (value, label, extra) => {
    this.setState({ permissionType: value });
  };

  changepermissionType = (value, option) => {
    this.setState({ _permissionType: value });
  };

  pageChange = (page, temp, _pricetype) => {
    let that = this;
    this.setState({ current: page }, () => {
      this.sendData();
    });
  };

  render() {
    let that = this;
    const {
      currentUserLoading,
    } = this.props;
    //表头
    const columns = [
      {
        title: '权限名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '管理编码',
        dataIndex: 'area',
        key: 'area',
      },
      {
        title: '描述',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '修改日期',
        dataIndex: 'number',
        key: 'number',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => {
          return (
            <div key={index}>
              <a href="javascript:;"
                onClick={() => {
                  that.changeUser(item.functionId, item.name, item.area, item.status, item.menuFun);
                }}
              >
                修改
              </a>
              &emsp;
              <a href="javascript:;"
                onClick={() => {
                  that.frozenUser(item.functionId);
                }}
              >
                {item.stateCode == '0' ? '禁用' : '启用'}
              </a>
            </div>
          );
        },
      },
    ];

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>权限管理</p>
              <p>PERMISSION PASSWORD</p>
            </div>
          </div>
          <div className='mrb15'>
          <Form layout="inline" align='center'>
              <FormItem>
                  <span className="label">权限名称：</span>
                  <Input
                    value={this.state.number}
                    data-inp="zdbh"
                    onChange={this.changeNumber.bind(this)}
                    placeholder="请输入工号"
                  />
              </FormItem>

              <Row gutter={24} style={{ textAlign: 'center'}}>
                  <Button icon='search' type="primary" className="evfilterbtn" onClick={this.sendData.bind(this)}>
                    查询
                  </Button>
                  &emsp;
                  <Button
                    onClick={this.resetForm.bind(this)}
                    type="primary"
                    htmlType="reset"
                    className="evfilterbtn" icon="reload"
                  >
                    重置
                </Button>
                &emsp;
                <Button
                  type="primary"
                  onClick={() => this.setModalVisible(true)}
                  htmlType="reset" icon="plus-circle"
                >
                  新建权限
              </Button>
            </Row>
          </Form>
          </div>

          <Row className="choicedBox">
            <Table
              bordered={true}
              scroll={{x:true}}
              align={'center'}
              columns={columns}
              dataSource={this.state.tableData}
              pagination={{
                defaultPageSize: this.state.pageSize,
                current: this.state.current,
                onChange: this.pageChange,
                total: this.state.totalSize,
                showTotal: total => `共 ${total} 项`
              }}
            />
          </Row>

          <Modal
            title="新建权限"
            wrapClassName="vertical-center-modal"
            visible={this.state.modalVisible}
            onOk={() => this.setModalVisible(false, true)}
            onCancel={() => this.setModalVisible(false, false)}
            width={830}
          >
            <Row gutter={24} className={styles.modalForm}>
              <Col span={8}>
              <span className={styles.label}>
                <span style={{ color: 'red' }}>*</span>权限名称：
              </span>
              <Input
                value={this.state.functionName}
                data-inp="zdbh"
                onChange={this.functionName.bind(this)}
                placeholder=""
              />
            </Col>
            <Col span={8}>
              <span className={styles.label}>
                <span style={{ color: 'red' }}>*</span>管理编码：
              </span>
              <Input
                value={this.state.functionCode}
                onChange={this.functionCode.bind(this)}
                data-inp="zldz"
                placeholder=""
              />
            </Col>
            <Col span={8}>
              <span className={styles.label}>权限描述：</span>
              <Input
                value={this.state.functionDesc}
                data-inp="zdbh"
                onChange={this.functionDesc.bind(this)}
                placeholder=""
              />
            </Col>
            <Col span={8}>
              <span className={styles.label}>
                <span style={{ color: 'red' }}>*</span>权限类型：
              </span>
              <Select
                defaultValue={this.state._permissionType}
                onChange={this.changepermissionType}
              >
                {this.state.permissionTypeList &&
                  this.state.permissionTypeList.map((item, index) => {
                    return (
                      <Select.Option key={index} value={item.dicId}>
                        {item.dicName}
                      </Select.Option>
                    );
                  })}
              </Select>
            </Col>
            {this.state._permissionType == 1 ? (
              ''
            ) : (
              <Col span={8}>
                  <span className={styles.label}>
                    <span style={{ color: 'red' }}>*</span>添加菜单：
                </span>
                  <TreeSelect
                    value={this.state.permissionType}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={this.state.orgTreeData}
                    treeDefaultExpandedKeys={['1']}
                    treeCheckable={true}
                    showCheckedStrategy={'SHOW_PARENT'}
                    allowClear={true}
                    onChange={this.addpermissionType}
                  />
                </Col>
              )}
            </Row>
          </Modal>
          <Modal
            title="修改权限"
            wrapClassName="vertical-center-modal"
            visible={this.state.modifyVisible}
            onOk={() => this.setmodifyVisible(false, true)}
            onCancel={() => this.setmodifyVisible(false, false)}
            width={830}
          >
            <Row gutter={24} className={styles.modalForm}>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>权限名称：
              </span>
                <Input
                  value={this.state.functionName}
                  data-inp="zdbh"
                  onChange={this.functionName.bind(this)}
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>管理编码：
              </span>
                <Input
                  value={this.state.functionCode}
                  onChange={this.functionCode.bind(this)}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>权限描述：</span>
                <Input
                  value={this.state.functionDesc}
                  data-inp="zdbh"
                  onChange={this.functionDesc.bind(this)}
                  placeholder=""
                />
              </Col>
              {this.state.showTree ? (
                <Col span={8}>
                  <span className={styles.label}>
                    <span style={{ color: 'red' }}>*</span>给该权限添加菜单功能：
                </span>
                  <TreeSelect
                    style={{ width: 300 }}
                    value={this.state.permissionType}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={this.state._orgTreeData}
                    placeholder="Please select"
                    treeDefaultExpandedKeys={['1']}
                    treeCheckable={true}
                    showCheckedStrategy={'SHOW_PARENT'}
                    allowClear={true}
                    onChange={this.addpermissionType}
                  />
                </Col>
              ) : (
                  ''
                )}
            </Row>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default permissionPassword;
